$.namespace("systemManage.resource.resourceList");
systemManage.resource.resourceList=function(){
	
	//查询参数
	var queryParam={};
	
	//当前查询列表总记录数
	var currentTotal;
	
	//初始化方法
	init();
	
	/**
	 * 初始化方法
	 */
	function init(){
		
	   /**
		* 查询列表
		*/
		$('#resource-datagrid').datagrid({
			url:ctxPath+'/systemManage/resource/findResourceList',
			loadFilter:pagerFilter,
			method:'post',
			rownumbers:true,
			singleSelect:false,
			pageSize:15, 
			pageList:pageArray,
			pagination:true,
			multiSort:false,
			fitColumns:true,
			fit:true,
			loadMsg:"正在努力加载...",
			columns:[[
				{ field:'checkbox',checkbox:true},
				{ field:'operate',title:'操作',width:110,formatter:updateOperateFormatter},
				{ field:'resourceName',title:'菜单名称',width:120,sortable:true},
				{ field:'code',title:'菜单编码',width:80,sortable:true},
				{ field:'url',title:'链接路径',width:180,sortable:true},
				{ field:'enabled',title:'是否可用',width:80,sortable:true,formatter:enabledFormatter},
				{ field:'sequence',title:'序号',width:50,sortable:true},
				{ field:'parentName',title:'父菜单',width:150},
				{ field:'level',title:'层级',width:50},
				{ field:'creatorName',title:'创建人',width:100,sortable:true},
				{ field:'creatorTrueName',title:'创建人名称',width:100,sortable:true},
				{ field:'createDate',title:'创建日期',width:180,sortable:true},
				{ field:'id',hidden:true}
				
				
			]],
			rowStyler: function(index,row){
				if (index%2==0){
					return 'background-color:#F4F4F4';
				}
			},
			onBeforeLoad:function(param){
				$.extend(param,queryParam);
			},
			onLoadSuccess:function(data){
				if(data.total==0){
					$(this).datagridTipInfo('noData');
				}else{
					$('.editcls').linkbutton({plain:true,iconCls:'icon-edit'});  
					$('.tonext').linkbutton({plain:true,iconCls:'icon-next-blue'});  
					$('.bindPermissionCls').linkbutton({plain:true,iconCls:'icon-advancedsettings'}); 
				}
				currentTotal=data.total;
			},
			onLoadError:function(){
				$(this).datagridTipInfo('error');
			}

		}); 

		/**
		 * 父菜单comboTree组件,当输入为空的时候清除之前选择的选项
		 * 根据输入的内容在tree中进行搜索
		 */
		$('#parentId').combotree({
		    url: ctxPath+'/systemManage/resource/findResourceTree',
		    editable: true,
		    keyHandler: {
		    	up: function(){},
		    	down: function(){},
		    	enter: function(){},
		    	query: function(q){
		    		//q为输入框中的文本
		    		if(util.isEmptyStr(q)){
		    			$('#parentId').combotree('clear');
		    		}
		    		var resourceTree = $('#parentId').combotree('tree');
	    			resourceTree.tree('doFilter', q);
		    		
		    	}
		    }
		});
		
		/**
		 * 菜单资源树形展示
		 */
		$('#resource-tree').tree({
			url: ctxPath+'/systemManage/resource/findResourceTree',
			method:'get',
			onClick:function(node){
				alert(node.text);
			}
		});
		
		
		$("#permissionIdList").combobox({
		    url:ctxPath+'/systemManage/permission/findAllEnabledPermission',
		    multiple:true,
		    editable:false,
		    value:[],
		    valueField:'id',
		    textField:'permissionName'
		});
		
	}
	

	
	
	/**
	 * 显示修改按钮
	 */
	function updateOperateFormatter(value,row,index){
		 var id=row.id;
		 var parentId=row.parentId;
		 var level=row.level;
		 var btn = '<a class="editcls" title="修改" onclick="systemManage.resource.resourceList.openUpdate('+id+')" href="javascript:void(0)"></a>';  
		 btn+='<a class="tonext" title="子菜单" onclick="systemManage.resource.resourceList.showSubMenu('+id+','+level+')" href="javascript:void(0)"></a>';
		 btn+= '<a class="bindPermissionCls" title="设置权限" onclick="systemManage.resource.resourceList.openPermission('+id+')" href="javascript:void(0)"></a>';  
		 return btn;
	}
	
	/**
	 * 给form中的元素绑定事件
	 */
	function formElementBindEvent(){

		/**
		 * 输入菜单名称后自动生成菜单编码
		 */
		$("#resourceName").textbox('textbox').bind("blur",function(event){
			var resourceName=$("#resourceName").textbox("getValue");
			var code=$("#code").textbox("getValue");
			if(util.isEmptyStr(code)){
				$.getJSON(ctxPath+'/systemManage/resource/generateResourceCode',{"resourceName":resourceName},function(data){
					if(data.returnCode=='success'){
						$('#code').textbox("setValue",data.returnData);
					}
				});
			}
			
		});
	}
	
	/**
	 * 对外的方法
	 */
	 return {
		 
		 /**
		  * 根据条件查询datagrid
		  */
		 queryList:function(param){
			 if($.isPlainObject(param)){
				 $.extend(queryParam,param);
			 }else{
				 var queryFormParam=$("#resource-queryForm").find(".textbox-value").objParam();
				 if(!util.isEmptyStr(queryParam.level))
				 queryFormParam.level=queryParam.level;
				 
				 if(!util.isEmptyStr(queryParam.parentId))
				 queryFormParam.parentId=queryParam.parentId;
				 
				 queryParam=queryFormParam;
			 }
			 $('#resource-datagrid').datagrid('load', queryParam);  
		 },
	 
		 /**
		  * 重置
		  */
		 reset:function(){
			 $('#resource-queryForm').form('reset');
		 },
		 
		 /**
		  * 打开添加窗口
		  */
		 openAdd:function(){
				$('#resourceForm').form('reset').form('disableValidation');
				$('#resource-dialog').dialog({
					closed: false,
					modal:true,
			        title: "添加菜单",
			        buttons: [{
			            text: '确定',
			            iconCls: 'icon-ok',
			            handler: add
			        }, {
			            text: '取消',
			            iconCls: 'icon-cancel',
			            handler: function () {
			                $('#resource-dialog').dialog('close');                    
			            }
			        }]
			    });
				
				formElementBindEvent();
				//自动设置序号的值：当前子项总数+1
				$("#sequence").textbox('setValue',currentTotal+1);
		 },
		 

		/**
		* 打开修改窗口
		*/
		 openUpdate:function(id){
			$('#resourceForm').form('reset').form('disableValidation');
			$.ajax({
				url:ctxPath+'/systemManage/resource/getResourceById',
				data:{'id':id},
				success:function(data){
					if(data.returnCode=='success'){
						//绑定值
						var returnData=data.returnData;
						$('#resourceForm').form('load', returnData);
						if(returnData.parentId==0){
							$('#parentId').combotree('clear');
						}
					}else{
						$('#resource-dialog').dialog('close');
						$.messager.alert('信息提示','没有找到该菜单信息！','info');
					}
				}	
			});
			
			$('#resource-dialog').dialog({
				closed: false,
				modal:true,
		        title: "修改菜单",
		        buttons: [{
		            text: '确定',
		            iconCls: 'icon-ok',
		            handler: update
		        }, {
		            text: '取消',
		            iconCls: 'icon-cancel',
		            handler: function () {
		                $('#resource-dialog').dialog('close');                    
		            }
		        }]
		    });
			
			formElementBindEvent();
			
		},
		
		
		/**
		* 删除记录
		*/
		remove:function(){
			$.messager.confirm('信息提示','确定要删除该记录？', function(result){
				if(result){
					var items = $('#resource-datagrid').datagrid('getSelections');
					if(items.length>0){
						
						$.ajax({  
						    type: "POST",  
						    url: ctxPath+'/systemManage/resource/removeResource',  
						    data: JSON.stringify(items), 
						    dataType:"json",  
						    contentType : 'application/json;charset=utf-8',
						    success: function(data){  
						    	if(data.returnCode=='success'){
						        	$.messager.alert('信息提示','提交成功！','info');
						        	$('#resource-datagrid').datagrid('reload');  
						    	}else if(data.returnCode=='exist_enabled'){
						    		$.messager.alert('信息提示','可用状态的菜单不能删除!','info');
						    		$('#permission-datagrid').datagrid('reload');
						    	}else{
						    		$.messager.alert('信息提示','删除失败！','info');
						    	}
						    },  
						    error: function(res){  
						    	$.messager.alert('信息提示','删除失败！','info');
						    }  
						}); 
						
					}else{
						$.messager.alert('信息提示','请选择要删除的数据！','info');
					}
					
					
				}	
			});
		},
		
		
		/**
		 * 显示子菜单
		 */
		showSubMenu:function(parentId,level){
			systemManage.resource.resourceList.reset();
			queryParam={};
			queryParam["parentId"]=parentId;
			queryParam["level"]=level+1;
			systemManage.resource.resourceList.queryList(queryParam);
		},
		
		/**
		 * 返回上一层菜单
		 */
		backParentMenu:function(){
			systemManage.resource.resourceList.reset();
			var level=queryParam["level"];
			if(level && level>1){
				queryParam={"level":level-1};
			}else{
				queryParam={"level":1}
			}
			systemManage.resource.resourceList.queryList(queryParam);
		},
		
		/**
		 * 打开权限设置窗口
		 */
		openPermission:function(id){
			//需要reset一下，form下的元素会保留之前的输入
			$('#bindPermissionForm').form('reset');
			$.ajax({
				url:ctxPath+'/systemManage/resource/getResourcePermissionById',
				data:{'id':id},
				success:function(data){
					if(data.returnCode=='success'){
						$("#resourceId").val(id);
						if(!util.isEmptyStr(data.returnData)){
							var permissionIds=data.returnData;
							$('#permissionIdList').combobox('setValue',permissionIds.split(","));
						}
							
					}else{
						$('#resource-dialog').dialog('close');
						$.messager.alert('信息提示','没有找到该菜单信息！','info');
					}
				}	
			});
			
			$('#bindPermission-dialog').dialog({
				closed: false,
				modal:true,
		        title: "菜单下的权限",
		        buttons: [{
		            text: '确定',
		            iconCls: 'icon-ok',
		            handler: bindPermission
		        }, {
		            text: '取消',
		            iconCls: 'icon-cancel',
		            handler: function () {
		                $('#bindPermission-dialog').dialog('close');                    
		            }
		        }]
		    });
		}


	 
	 }

	 

	/**
	* 添加记录
	*/
	function add(){
		$('#resourceForm').form({   
		    url:ctxPath+'/systemManage/resource/insertResource', 
		    onSubmit: function(param){  
		    	if(!util.isEmptyStr(queryParam.level))
		    		param.level=queryParam.level;
				 
				if(!util.isEmptyStr(queryParam.parentId))
					param.parentId=queryParam.parentId;
				 
		    	return $(this).form('enableValidation').form('validate'); 
		    },   
		    success:function(data){
		    	data=JSON.parse(data);
		        if(data.returnCode=='success'){
		        	$.messager.alert('信息提示','提交成功！','info');
					$('#resource-dialog').dialog('close');
					$('#resource-datagrid').datagrid('reload'); 
					$('#resource-tree').tree('reload');
		        }else{
		        	$.messager.alert('信息提示','提交失败！','info');
		        }   
		    }   
		}); 
		$('#resourceForm').submit();
	}
	

	/**
	* 修改记录
	*/
	function update(){
		$('#resourceForm').form({   
		    url:ctxPath+'/systemManage/resource/updateResource',  
		    onSubmit: function(param){  
		    	return $(this).form('enableValidation').form('validate'); 
		    },   
		    success:function(data){ 
		    	data=JSON.parse(data);
		        if(data.returnCode=='success'){
		        	$.messager.alert('信息提示','提交成功！','info');
					$('#resource-dialog').dialog('close');
					$('#resource-datagrid').datagrid('reload');  
					$('#resource-tree').tree('reload');
		        }else{
		        	$.messager.alert('信息提示','提交失败！','info');
		        }   
		    }   
		}); 
		$('#resourceForm').submit();
	}
	
	/**
	 * 设置菜单下的权限
	 */
	function bindPermission(){
		$('#bindPermissionForm').form({   
		    url:ctxPath+'/systemManage/resource/bindPermission', 
		    onSubmit: function(param){  
		    	return true;
		    },
		    success:function(data){
		    	data=JSON.parse(data);
		        if(data.returnCode=='success'){
		        	$.messager.alert('信息提示','提交成功！','info');
					$('#bindPermission-dialog').dialog('close');
		        }else{
		        	$.messager.alert('信息提示','提交失败！','info');
		        }   
		    }   
		}); 
		$('#bindPermissionForm').submit();
	}


	
}();

